package com.liqi.frame.comm.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import java.util.Properties;

/**
 * 外部配置文件
 */
@Slf4j
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        try {
            String configPath = environment.getProperty("configPath");
            if (StringUtils.isNotBlank(configPath)) {
                yaml.setResources(new FileSystemResource(configPath));
                Properties object = yaml.getObject();
                if (object!=null) {
                    PropertiesPropertySource propertySource = new PropertiesPropertySource("myEnvironment", object);
                    environment.getPropertySources().addFirst(propertySource);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}